// pages/lifeService/foodMap/map.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: 29.764625,
    longitude: 106.556256,
    // 组件参数设置，传递到组件
    defaultData: {
      title: "美食地图", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    menuTop: app.globalData.menuTop,
    menuHeight: app.globalData.menuHeight,
    //首页展示的商家图标
    markers: [],

    //分类下的商家列表
    shopList: [],
    showShopContent: false,

    menuList: [],
    chooseMenuId: 0,
    showShop: false,

    shareTitle: '',
    shareImg: '',
    openid: '',
    img_path_content: '', //内容图路径
    curShopPostion: '',
    tel: '',
    //  stsat *************** 地图层的大分类列表
    classificationTab: [{
        id: 0,
        name: '全部'
      },
      {
        id: 1,
        name: '吃'
      },
      {
        id: 2,
        name: '喝'
      },
      {
        id: 3,
        name: '玩'
      },
      {
        id: 4,
        name: '乐'
      },
    ],
    classificationIndex: 0,
    // tabIndex:1,
    //  end ***************
    is_csh: 1 //第一次初始化数据
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  tel() {
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.tel
    })
  },
  goBack() {
    let that = this;
    that.setData({
      showShop: false
    });
  },
  markertap(e) {
    let that = this;
    let markerId = e.detail.markerId;
    let markers = that.data.markers;
    // 改变icon显示方式 **** start
    // for (var i = 0; i < markers.length; i++) {
    //   markers[i].iconPath = app.baseUrl + "images/lifeservice/mapIcon1.png";
    // }
    const icon = markers[markerId].iconImg
    markers[markerId].iconPath = app.baseUrl + `images/lifeservice/iconImg${icon}${icon}.png`;
    // ****end
    var tel = that.data.markers[markerId].tel;
    that.setData({
      markers,
      showShopContent: true,
      img_path_content: markers[markerId].imgPathContent,
      curShopPostion: markers[markerId],
      tel: tel
    });
    app.slideupshow(this, 'slideUpAnimate', 0, 1);
    var timeout2 = setTimeout(() => {
      app.show(this, 'hideBtnAnimate', 1);
      clearTimeout(timeout2)
    }, 800);
  },
  dh() {
    let that = this;
    let curShopPostion = that.data.curShopPostion;
    const mapContext = wx.createMapContext('map');
    console.log(curShopPostion)
    mapContext.openMapApp({
      longitude: Number(curShopPostion.longitude),
      latitude: Number(curShopPostion.latitude),
      destination: curShopPostion.callout.content,
      success: function () {
        console.log("成功将地图中心移到定位点22222")

      },
      fail: function (e) {
        console.log(e)

      }
    })
  },
  shop(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    let marker = item.marker;
    let markerId = marker.id;
    let markers = that.data.markers;
    let markerArr = [];

    for (var i = 0; i < markers.length; i++) {
      markers[i].iconPath = app.baseUrl + `images/lifeservice/iconImg${markers[i].iconImg}.png`; // ****
      let obj = {};
      obj.latitude = markers[i].latitude;
      obj.longitude = markers[i].longitude;
      markerArr.push(obj)
    }
    const icon = markers[markerId].iconImg
    markers[markerId].iconPath = app.baseUrl + `images/lifeservice/iconImg${icon}${icon}.png`; // 点击变图标 ****
    that.setData({
      markers,
      curShopPostion: marker,
      showShop: false,
      showShopContent: true,
      img_path_content: item.imgPathContent
    });
    // 获取地图上下文
    const mapContext = wx.createMapContext('map');

    // 平滑移动地图的中心点
    mapContext.moveToLocation({
      latitude: Number(marker.latitude),
      longitude: Number(marker.longitude),
      duration: 1000, // 移动的动画时长，单位毫秒
      success: function () {
        console.log("成功将地图中心移到定位点")
        var timeout1 = setTimeout(() => {

          app.slideupshow(that, 'slideUpAnimate', 0, 1);
          clearTimeout(timeout1)
          var timeout2 = setTimeout(() => {
            app.show(that, 'hideBtnAnimate', 1);
            clearTimeout(timeout2)
          }, 500);
        }, 300);
      }
    });

  },
  goShopList() {
    let that = this;
    that.setData({
      showShop: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var isPrev = options.isPrev;
    if (isPrev != 1) {
      that.setData({
        ['defaultData.goUrl']: '/pages/lifeService/index'
      });
    }
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getLifeServiceFoodMapPageInfo(res.data.openid, 0, 0, 1, 0, 0);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getLifeServiceFoodMapPageInfo(openid, 0, 0, 1, 0, 0);
    }

    //调用分享
    that.getShareInfo();

  },

  //获取本页数据
  getLifeServiceFoodMapPageInfo(openid, cate_id, big_cate_id, is_csh, is_change_big, is_change_small) {
    //return;
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getLifeServiceFoodMapPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'cate_id': cate_id,
        'big_cate_id': big_cate_id,
        'is_csh': is_csh,
        'is_change_big': is_change_big,
        'is_change_small': is_change_small
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          res.data.markers.forEach(el => {
            el.callout.content1 = el.callout.content
            // ****  start
            el.iconPath = app.baseUrl + `images/lifeservice/iconImg${el.iconImg}.png`;
            el.width = 30;
            el.height = 30;
            el.callout['anchorY'] = -5;
            // ****  end
            el.callout['color'] = "#fff";
            el.callout['bgColor'] = "#6294DA"; //"rgba(98,148,218, 0.7)";
            el.callout['padding'] = "5";
            el.callout['borderRadius'] = "19";
          })
          //重新赋值后台请求数据
          //判断是否需要更新分类
          if (is_csh == 1) {
            //初始化更新分类
            that.setData({
              menuList: res.data.menuList,
              shopList: res.data.shopList,
              // markers: res.data.markers,
              oldMarkers: res.data.markers, // 备份用于筛选 *****
              classificationTab: res.data.bigCateList
            });
          } else {
            //点击某个分类不用再去更新分类菜单
            that.setData({
              shopList: res.data.shopList,
              // markers: res.data.markers,
              oldMarkers: res.data.markers, // 备份用于筛选 *****
            });

            //判断是否更新了小分类
            if (res.data.is_edit_menu == 1) {
              that.setData({
                menuList: res.data.menuList
              });
            }
          }

          //判断是否是第一次初始化数据
          if (is_csh == 1) {
            //修改初始化状态
            that.setData({
              is_csh: 0
            });
          }
          that.bindregionchange({
            detail: {
              scale: 12.2
            }
          })
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },
  // 地图切换吃喝玩乐  stsat ***************
  mapTypeHand(e) {
    const {
      id
    } = e.currentTarget.dataset.item
    // 全部
    if (id === 0) {
      this.setData({
        markers: this.data.oldMarkers,
        classificationIndex: id,
        chooseMenuId: 0
      });
      //重新请求数据
      this.getLifeServiceFoodMapPageInfo(this.data.openid, 0, id, 0, 1, 0);
      return;
    }
    // 过滤当前点击的
    const filterType = this.data.oldMarkers.filter(el => el.iconImg === id)
    const filterList = filterType.map(el => ({
      ...el,
      iconPath: app.baseUrl + `images/lifeservice/iconImg${id}.png`
    }))
    this.setData({
      markers: filterList,
      classificationIndex: id,
      chooseMenuId: 0
    });
    //重新请求数据
    this.getLifeServiceFoodMapPageInfo(this.data.openid, 0, id, 0, 1, 0);
  },
  //点击地图内层的大分类
  changeClassification(e) {
    const item = e.currentTarget.dataset
    this.setData({
      classificationIndex: item.index,
      chooseMenuId: 0
    });

    //重新请求数据
    this.getLifeServiceFoodMapPageInfo(this.data.openid, 0, item.index, 0, 1, 0);
  },
  //  end ***************

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {
        pid: 8
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  bindregionchange(e) {
    console.log(e);
    const info = wx.getSystemInfoSync()
    if (info.system.indexOf('iOS') > -1) {
      // this.data.markers.forEach(el=>{
      //   el.callout.bgColor = "rgba(98,148,218, 0.7)";
      // })
      this.setData({
        markers: this.data.oldMarkers
      })
    } else {
      const {
        scale,
        type
      } = e.detail
      let newmarkers = this.data.oldMarkers
      if (scale >= 9) {
        newmarkers.forEach(el => {
          el.callout.content = '';
          el.callout.bgColor = 'transparent';
          el.callout.anchorY = -5
        })
      }
      if (scale >= 12) {
        newmarkers.forEach((el, i) => {
          if (i < 5) {
            el.callout.content = el.callout.content1;
            el.callout.bgColor = "#6294DA";
            el.callout.padding = 10;
          }
        })
      }
      if (scale >= 18) {
        newmarkers.forEach((el, i) => {
          if (!el.callout.content) {
            el.callout.content = el.callout.content1;
            el.callout.bgColor = "#6294DA";
            el.callout.padding = 10;
          }
        })
      }

      this.setData({
        markers: newmarkers
      })
    }
  },
  hideShopContent() {
    app.show(this, 'hideBtnAnimate', 0);
    app.slideupshow(this, 'slideUpAnimate', 200, 0);
    let that = this;
    let markers = that.data.markers;
    // for (var i = 0; i < markers.length; i++) {
    //   markers[i].iconPath = app.baseUrl + "images/lifeservice/mapIcon1.png";
    // }
    // 恢复iocn ****stsrt
    const restid = this.data.curShopPostion
    markers[restid.id].iconPath = app.baseUrl + `images/lifeservice/iconImg${restid.iconImg}.png`;
    // ****end
    that.setData({
      markers
    });
    var timeout1 = setTimeout(() => {
      this.setData({
        showShopContent: false
      })
      clearTimeout(timeout1)
    }, 800);
  },

  //切换菜谱分类
  changeTab(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;

    wx.hideLoading();
    that.setData({
      chooseMenuId: id,
    });
    //重新请求加载数据
    that.getLifeServiceFoodMapPageInfo(that.data.openid, id, that.data.classificationIndex, 0, 0, 1);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/lifeService/foodMap/map',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})